import { defineStore } from 'pinia'
import { secureStorage } from '@/utils/secureStorage'

// 用户认证相关的store
export const useUserStore = defineStore('user', {
  // 状态
  state: () => ({
    token: secureStorage.get('token') || '',
    userInfo: secureStorage.get('userInfo') || null,
    isLoggedIn: !!secureStorage.get('token')
  }),

  // 计算属性
  getters: {
    hasLogin: state => !!state.token,
    getUserInfo: state => state.userInfo
  },

  // 方法
  actions: {
    // 设置用户登录信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      secureStorage.set('userInfo', userInfo)
    },

    // 设置登录令牌
    setToken(token) {
      this.token = token
      this.isLoggedIn = true
      secureStorage.set('token', token)
    },

    // 登录成功后调用
    loginSuccess({ token, userInfo }) {
      this.setToken(token)
      this.setUserInfo(userInfo)
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      secureStorage.remove('token')
      secureStorage.remove('userInfo')
    }
  }
})
